package com.nuoniu.sibanyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.SysDictType;
import com.nuoniu.sibanyun.entity.dto.DictDataSaveDto;
import com.nuoniu.sibanyun.entity.dto.DictDataSearchDto;
import com.nuoniu.sibanyun.entity.dto.DictTypeSaveDto;
import com.nuoniu.sibanyun.entity.dto.DictTypeSearchDto;
import com.nuoniu.sibanyun.mapper.SysDictTypeMapper;
import com.nuoniu.sibanyun.service.ISysDictDataService;
import com.nuoniu.sibanyun.service.ISysDictTypeService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 字典类型表 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-05-25
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {


    @Autowired
    private ISysDictDataService sysDictDataService;

    @Override
    public Page<SysDictType> page(DictTypeSearchDto dictTypeSearchDto) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(dictTypeSearchDto.getDictName())){
            queryWrapper.like("dict_name",dictTypeSearchDto.getDictName());
        }
        if(StringUtils.isNotBlank(dictTypeSearchDto.getDictType())){
            queryWrapper.like("dict_type",dictTypeSearchDto.getDictType());
        }
        if(null != dictTypeSearchDto.getIsSys()){
            queryWrapper.eq("is_sys",dictTypeSearchDto.getIsSys());
        }
        if(null != dictTypeSearchDto.getStatus()){
            queryWrapper.eq("status",dictTypeSearchDto.getStatus());
        }

        queryWrapper.ne("status",1);
        queryWrapper.and(wrapper -> wrapper.eq("company_id", 1).or().eq("company_id", userInfo.getCompanyId()));
        queryWrapper.orderByAsc("show_sort");
        queryWrapper.orderByAsc("create_date");
        Page<SysDictType> page = page(dictTypeSearchDto.getPage(),queryWrapper);
        return page;
    }

    @Override
    public boolean saveOrUpdate(DictTypeSaveDto dictTypeSaveDto, HttpServletRequest request) {
        if(null == dictTypeSaveDto) throw new NuoNiuException("保存失败，参数都为空");
        LocalDateTime now = LocalDateTime.now();
        UserInfo userInfo = UserThreadLocal.get();
        SysDictType sysDictType = new SysDictType();
        BeanUtils.copyProperties(dictTypeSaveDto,sysDictType);

        SysDictType dictType = baseMapper.getByCode(dictTypeSaveDto.getDictCode());
        if(dictType != null && (sysDictType.getId() == null || !(sysDictType.getId().equals(dictType.getId()))) ) {
            throw new NuoNiuException("编码已存在");
        }

        if(null == sysDictType.getId()){
            sysDictType.setCreateDate(now);
            sysDictType.setCreateBy(userInfo.getUserId());
            sysDictType.setCompanyId(userInfo.getCompanyId());
            if(userInfo.getUserName().equals("system")) {
                sysDictType.setIsSys(true);
                sysDictType.setIsUpdate(true);
            } else {
                sysDictType.setIsSys(false);
                sysDictType.setIsUpdate(false);
            }
        } else {
            SysDictType type = this.getById(dictTypeSaveDto.getId());
            if(!userInfo.getCompanyId().equals(type.getCompanyId())) {
                throw new NuoNiuException("无此权限，请联系管理员");
            }
        }


        sysDictType.setUpdateBy(userInfo.getUserId());
        sysDictType.setUpdateDate(now);
        boolean b = saveOrUpdate(sysDictType);
        return b;
    }

    @Override
    public boolean updateStatus(Long id, Integer status, HttpServletRequest request) {
        LocalDateTime now = LocalDateTime.now();
        Integer currentUserId = UserThreadLocal.get().getUserId();
        SysDictType sysDictType = new SysDictType();
        sysDictType.setId(id);
        sysDictType.setStatus(status);
        sysDictType.setUpdateBy(currentUserId);
        sysDictType.setUpdateDate(now);
        boolean b = updateById(sysDictType);
        return b;
    }

    @Override
    public boolean delete(Long id, HttpServletRequest request) {
        boolean isHaveDictData = sysDictDataService.isHaveDictData(id);
        if(isHaveDictData) throw new NuoNiuException("删除失败，请先删除字典数据");
        removeById(id);
        return true;
    }

    @Override
    public List<DictTypeSaveDto> getDictDataAll() {
        List<DictTypeSaveDto> dictTypeSaveDtos = baseMapper.getAll();
        for(DictTypeSaveDto dto : dictTypeSaveDtos) {
            List<DictDataSaveDto> dataSaveDtos = sysDictDataService.getByType(dto.getId());
            dto.setDictDatas(dataSaveDtos);
        }
        return dictTypeSaveDtos;
    }

}
